import { ref, watch } from 'vue';

export function useHistory<T>(initialState: T) {
  const history = ref<T[]>([JSON.parse(JSON.stringify(initialState))]);
  const currentIndex = ref(0);
  
  const state = ref<T>(JSON.parse(JSON.stringify(initialState)));
  
  const pushState = (newState: T) => {
    // 深拷贝状态以避免引用问题
    const copiedState = JSON.parse(JSON.stringify(newState));
    
    // 移除当前索引之后的所有状态
    history.value = history.value.slice(0, currentIndex.value + 1);
    history.value.push(copiedState);
    currentIndex.value = history.value.length - 1;
    state.value = copiedState;
  };
  
  const undo = () => {
    if (canUndo.value) {
      currentIndex.value--;
      state.value = JSON.parse(JSON.stringify(history.value[currentIndex.value]));
    }
  };
  
  const redo = () => {
    if (canRedo.value) {
      currentIndex.value++;
      state.value = JSON.parse(JSON.stringify(history.value[currentIndex.value]));
    }
  };
  
  const canUndo = ref(false);
  const canRedo = ref(false);
  
  watch(currentIndex, (val) => {
    canUndo.value = val > 0;
    canRedo.value = val < history.value.length - 1;
  }, { immediate: true });
  
  return {
    state,
    pushState,
    undo,
    redo,
    canUndo,
    canRedo
  };
}